package com.sunwoda.springbootshiro.controller;

import com.sunwoda.springbootshiro.entity.User;
import com.sunwoda.springbootshiro.realm.MyRealm;
import com.sunwoda.springbootshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-09-26 19:46:24
 */
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public User selectOne(Long id) {
        return this.userService.queryById(id);
    }

    /**
     * @description: null
     * @param:
     * @return:
     * @author shiguorang
     * @date: 2021/9/26 19:48
     */
    @PostMapping(value = "getAll")
    public List<User> getAll(@RequestBody User user){
        return null;
    }

    /**
     * @description: null
     * @param:
     * @return:
     * @author shiguorang
     * @date: 2021/9/26 19:52
     */
    @PostMapping(value = "/inilogin")
    public String iniLogin(@RequestBody User user){
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(new IniRealm("classpath:shiro.ini"));
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(),user.getPassword());
        try {
            subject.login(token);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (subject.isAuthenticated()){
            return "认证成功";
        }else {
            return "认证失败";
        }
    }

    /**
     * @description: null
     * @param:
     * @return:
     * @author shiguorang
     * @date: 2021/9/26 19:52
     */
    @PostMapping(value = "/loginVersion2")
    public String loginVersion2(@RequestBody User user){
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(new MyRealm());
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(),user.getPassword());
        try {
            subject.login(token);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (subject.isAuthenticated()){
            return "认证成功";
        }else {
            return "认证失败";
        }
    }

}